<template>
  <div class="comment">
    <h1>发表评论</h1>
    <hr />
    <textarea class="text" placeholder="请输入内容" v-model="content" autofocus ref="contentRef"></textarea>
    <van-button type="danger" class="btn-post" @click="postComment">提交</van-button>
    <div class="comment-list" v-for="(comment,index) in comments" :key="comment.id">
      <div class="comment-tilte">
        <span>第{{index+1}}楼</span>
        <span>用户：{{comment.user_name}}</span>
        <span>发表时间：{{comment.add_time}}</span>
      </div>
      <div class="comment-item">{{comment.content}}</div>
    </div>
    <van-button type="danger" plain class="btn-post" @click="getMore">{{text}}</van-button>
  </div>
</template>
<script>
export default {
  data: () => ({
    comments: [],
    content: '',
    pageindex: 0,
    hasFlag: true
  }),
  created () {
    this.getComments()
  },
  props: ['id'],
  methods: {
    async getComments () {
      if (this.hasFlag !== true) return
      this.pageindex++
      const {
        data: { status, message, count }
      } = await this.$http.get(
        `api/getcomments/${this.id}?pageindex=${this.pageindex}`
      )
      if (status !== 0) return this.$Tost(message)
      // console.log(message)
      // this.comments = message
      this.comments = this.comments.concat(message)
      this.hasFlag = this.pageindex * 2 < count
      console.log(this.hasFlag)
    },
    async postComment () {
      if (this.content.length === 0) return this.$Toast('输入内容不能为空')
      const {
        data: { status, message }
      } = await this.$http.post(`api/postcomment/${this.id}`, {
        content: this.content
      })
      if (status !== 0) return this.$Tost(message)
      this.comments.unshift({
        id: Date.now(),
        user_name: '匿名用户',
        add_time: Date.now(),
        content: this.content
      })
      this.content = ''
      this.$refs.contentRef.focus()
    },
    getMore () {
      this.getComments()
    }
  },
  computed: {
    text () {
      return this.hasFlag !== true ? '被掏空了' : '加载更多'
    }
  }
}
</script>
<style lang="less" scoped>
.comment {
  .text {
    height: 150px;
    width: 100%;
  }
  .btn-post {
    width: 100%;
  }
  .comment-tilte {
    margin-top: 16px;
    font-size: 12px;
    .comment-tilte {
      background: #ccc;
    }
  }
}
</style>
